<?php

namespace StarCloud\Library\Sdk;

use Framework\DiServices\HttpClient;
use KubAT\PhpSimple\HtmlDomParser;
use Phalcon\Db\Column;
use Phalcon\Di;
use StarCloud\Library\Exception;
use StarCloud\Library\HttpCurl;
use StarCloud\Models\Doumvip\KsDayIncome;
use StarCloud\Models\Doumvip\TiktokNew;
use StarCloud\Models\Doumvip\UcDayIncome;
use StarCloud\Services\BaseService;

class UcBot
{
    use HttpCurl;

    /* @var $httpClient HttpClient */
    private $httpClient = null;

    public function __construct()
    {
        $this->httpClient = Di::getDefault()->get('httpClient');
        $this->cacheClass = Di::getDefault()->get('redis');
    }

    public function getConfig()
    {
        return[
            'platform' => [
                ["label" => "私域", "value" => "私域",],
                ["label" => "抖音", "value" => "抖音",],
                ["label" => "快手", "value" => "快手",],
                ["label" => "小红书", "value" => "小红书",],
                ["label" => "B站", "value" => "B站",],
                ["label" => "头条", "value" => "头条",],
                ["label" => "拼多多", "value" => "拼多多",],
                ["label" => "公众号", "value" => "公众号",],
                ["label" => "视频号", "value" => "视频号",],
                ["label" => "淘宝", "value" => "淘宝",],
                ["label" => "微博", "value" => "微博",],
                ["label" => "知乎", "value" => "知乎",],
                ["label" => "其他", "value" => "其他",],
            ],
            'account_type' => [
                ["label" => "视频-dm", "value" => "wp101",],
                ["label" => "app-游戏/教程", "value" => "wp102",],
                ["label" => "图片-壁纸/头像", "value" => "wp103",],
                ["label" => "音频", "value" => "wp104",],
                ["label" => "文本-阅读", "value" => "wp106",],
                ["label" => "图片-漫画/绘画", "value" => "wp107",],
                ["label" => "其他视频-mng", "value" => "wp109",],
                ["label" => "学习-公考/考研", "value" => "wp201",],
                ["label" => "学习-k1", "value" => "wp202",],
                ["label" => "其他学习", "value" => "wp203",],
            ],
        ];
    }

    public function getHeader()
    {
        return [
            'Content-Type' => 'application/json',
            'Cookie' => 'SSO_LANG_V2=zh-CN; cna=c495Hk6o1ykBASQOBF23FL2M; ug_middle_system_USER_COOKIE_V3=ST151.jRrJ8zPks9thsvR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kVMiD2H87qnhsSh5_OjVsMtYcezo5W6yjnEkAWmXMOtGOFWfNJEtyQlfBMgzegUVswRjg; isg=BFJSBl7qYMbi45_j7WhDAnqUox40Y1b92tzKpxyoJIXwL_0pBfC7DMoJn4sTb86V',
        ];
    }

    public function getHeaderKKSite()
    {
//        https://union.quark.cn/account_manage/sitelist.php?omit=1
        return [
            'Content-Type' => 'application/json',
            'Cookie' => 'closeMe-110030-505=close; PHPSESSID=iu6gi8ll8gg0ce6qub50emfqn7; cs_account=KK_KOL_DMSS_KL'
        ];
    }

    public function getSites($page = 1)
    {
        $url = 'https://union.quark.cn/account_manage/sitelist.php?omit=1&page=' . $page;
        $response = $this->httpClient->sendGetRequest($url , [], $this->getHeaderKKSite());

        $html = $response->getBody()->getContents();

        $html = preg_replace('/<script\b[^>]*>(.*?)<\/script>/is', '', $html);

        $html = preg_replace('/<style\b[^>]*>(.*?)<\/style>/is', '', $html);
        try {
            $dom = HtmlDomParser::str_get_html($html);
            foreach($dom->find('.account-c') as $item) {
                $trs = $item->find('tr');
                if (count($trs) == 2) {
                    var_dump("站点数据为空");
                    break;
                }
                foreach($trs as $trIndex => $tr) {
                    if ($trIndex == 0) {
                        continue;
                    }
                    $tds = $tr->find('td');

                    $site = '';
                    foreach ($tds as $index => $td) {
                        if ($index == 2) {
                            $site = $td->find('div')[0]->innertext;
                        }
                    }
                    $siteInfo = explode('_', $site);
                    var_dump($siteInfo);
                    if (count($siteInfo) == 5) {
                        $record = TiktokNew::findFirst([
                            'conditions' => 'dyid = :dyid: and type = :type:',
                            'bind' => ['dyid' => $siteInfo[3], 'type' => TiktokNew::APP_ID_KKSS]
                        ]);
                        if ($record) {
                            TiktokNew::batchUpdate([
                                'conditions' => 'dyid = :dyid: and type = :type:',
                                'bind' => ['dyid' => $siteInfo[3], 'type' => TiktokNew::APP_ID_KKSS]
                            ], ['ucss_state' => 1, 'state' => 1]);
                            var_dump("success:" . $siteInfo[3]);
                        } else {
                            var_dump("miss:" . $siteInfo[3]);
                        }
                    }
                }
            }
        }catch (\Exception $e) {
            var_dump($e->getMessage(), $e->getTraceAsString());
        }
    }


    public function getHeaderKKOrder()
    {
        return [
            'Cookie' => 'closeMe-77594-505=close; closeMe-105857-505=close; closeMe-110030-505=close; b-user-id=1994bf1b-2e15-5969-2b46-d7b09e17205f; _UP_A4A_11_=wb9681dd556e4f6585a4fae0a5a1df5b; cna=WZTEHxSqxlgCARsRWp03Y+6e; __sdid=AAT+qmdBY0JnQOEJYlRB/VpKqM+WMvcBEod3765s7iI54579Y9e1tjQ8q3GPmeBns1w=; _UP_D_=pc; isg=BOjoR9QXG-Wp0TbZ5OuQA5PSudD6EUwbnQN6PaIZFWNW_YhnSiKAq3h-8ZUNTQTz; tfstk=gSxsFc47_IKUGmNHIfHFNh1DnjjjaIiPX-6vEKEaHGI9HiOCTOzZSZlXRIdF6lSODwIdnt-NBZCT9pBRi1I271WvOKdtItkMceqXEKxZIikGjdjcDblr4bJMIic1UcBnTpHAni6TjJr_bdjcDXyUD4oWIQdU_uKADvsd3OFADPCxdkB59lBYXtFKdtfdDOEOByEdFtfABtdvpv6c9sIADvxgf9k1tdM_q3EI5ybkB6ZYDhnc5_T_uoEv9O_6DdCCCOtCCN1R8AsbG39JB3XXmYUfGF89_9AjVXsJrBtfyiibxGJWJC_B5jZC-epkDwTnNzvkHLYARnNtQQpvsHsGV4U6wC9WlGAZ3rXBlKKljN27DIOpEUj9XjqNsEppD6-t3o1JzLjCKnl3XsTpkh7Gm5hfiH9pXEsrlu57G8abdaqfd_kIdr4mshOo2ZGdY3QOK9lqdvaynNBhdeHIdr4cW9XF9vMQzKf..; _pk_id.29d58fe8f7ec.bc25=d644c856-39ad-4cf0-a082-4d38bab71fd3.1723615652.7.1735359493.1735184646.; PHPSESSID=5o5jckc9k31t373lqh9v78dtt5; cs_account=KK_KOL_DMSS'
        ];
    }

    public function getHeaderOrder()
    {
        return [
            'Cookie' => 'closeMe-77455-505=close; PHPSESSID=o1bvgi0p2mjn0b10kq6v1fkn47; SSO_LANG_V2=zh-CN; cna=lpkbH2DkHS0CARsQkSnQfiLM; isg=BJWV1NmSX0A3aXu8LHx--2bipJdPkkmkeKtGcBc7MI3xbrNg2eaAdiVvPHJY7mFc; cs_account=UC_KOL_DMWL; _UP_28A_52_=582; _UP_A4A_11_=wb96715024a44aada9e080d2661a7516; _UP_D_=pc; tfstk=fIeKwcsndGKLpA5udk1gqswRfbIGiJEeWyrXE40HNPUTruZnNvDke73TDJc58u4tyzqrRJmn-0a8SVko-JV3wHyTkLvh86rWeYD5oZXcnkoEUY_DrOTXWeooDp6oNX96Tt42YZXcnk_hJ72RogovK1lsVYiINYt1XmgsV0aSRfTsDmkSPzM5XViE0H9IAXTsffx5yVtIrLFJ0k7x-g-WeLetfao0v_J-jJiK9qZQpL95cDhKlkgOo0NIgbUK9RXpuDF_DyoLztJEdbF7KAwC5E3ztmkI28SXw4h8LAn8_wd3kPFjB2wRDKD3LkNjN-_yNkks5vi46ZpEKo3tKJHf3egusoe-287PBrE707GTe9LqSjo54Se0HI12oqnk9GI9aQlIjSvei5XpXJuxXqjdeQRr_GotoGI9aQlIbc3cvTdyafSN.'
        ];
    }

    public function parseBody(&$body)
    {
        $body['spaceId'] = 1277;
        $body['tenantId'] = 'uc';
        $body['bizType'] = 2;
        $body['supplierId'] = 456;

        return $body;
    }

    public function applyBlog($uid, $name, $phone = "", $accountType = "", $platformName = "", $homePage = "")
    {
        $record = TiktokNew::getRecordOne($uid, $phone, TiktokNew::APP_ID_UC);
        if ($record && $record->getState() != -2) {
            throw new \StarCloud\Library\Exception(9999, 'UC网盘账号已存在');
        }

        $list = $this->getBlogApplyList(0, "", ['phone' => $phone]);

        if (!empty($list)) {
            foreach ($list as $item) {
                if ($item['auditStatus'] == 'AUDITING') {
                    throw new Exception(9999, '不用重复提交正在审核中');
                }
                if ($item['auditStatus'] == 'PASS') {
                    throw new Exception(9999, 'UC网盘账号已存在');
                }
            }
        }

        /**
         * "supplierId" => 456,
        "phone" => "18510043927",
        "accountType" => "wp107",
        "platformName" => "快手",
        "homePage" => "https://v.kuaishou.com/bkHsus",
         */
        if ($platformName == '私域') {
            $homePage = "https://alidocs.dingtalk.com/i/nodes/lyQod3RxJKddBydxiZ1xx1dL8kb4Mw9r?
corpId=ding7b760938cc34aa7e35c2f4657eb6378f&utm_medium=im_card&iframeQuery=utm_medium
%3Dim_card%26utm_source%3Dim&utm_scene=person_space&utm_source=im";
        }
        $body = [
            "blogger" => $name,
            "extraField" => "1",
            "phone" => $phone,
            "accountType" => $accountType,
            "platformName" => $platformName,
            "homePage" => $homePage,
            "settlementMethod" => "PWID",
            "pass" => true,
        ];

        $url = "https://material-ug.uc.cn/material/2.0/blogger_apply?spaceId=1277&tenantId=uc";

        $this->parseBody($body);

        $response = $this->httpClient->sendPostRequest($url, $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);
        Di::getDefault()->get("logger")->info("uc_log:" . json_encode($json));

        if (isset($json['success']) && $json['success'] == true) {
            TiktokNew::newUcUser($uid, $name, $phone);
            return $json;
        } else {

            throw new \StarCloud\Library\Exception(9999, $json['msg'] ?? "提交失败");
        }
    }

    public function submitAudit($item)
    {
        $body = $this->parseBody($item);

        $url = "https://material-ug.uc.cn/material/2.0/blogger_apply/audit?SPACE_ID=1277&TENANT_ID=uc&spaceId=1277&tenantId=uc";

        $response = $this->httpClient->sendPostRequest($url , $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);

        if (isset($json['success']) && $json['success'] == true) {
            return [
                true, "success"
            ];
        }

        return [false, $json['msg']];
    }

    public function getBlogApplyList($page = 0, $status, $params = [])
    {
        $body = [
            'currentPage' => $page,
            'pageSize' => 200,
            'showSensitive' => 'true',
            'auditStatus' => strval($status)
        ];

        $this->parseBody($body);

        $body = array_merge($body, $params);

        $url = "https://material-ug.uc.cn/material/2.0/blogger_apply/list?";

        $response = $this->httpClient->sendGetRequest($url . http_build_query($body) , $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);
        if (isset($json['success']) && $json['success'] == true) {
            return $json['data']['data_list'];
        }

        return [];
    }

    public function getkkssOrderByDate($date)
    {
        $url = "https://union.quark.cn/account_manage/mycount_site.php?pid=6004&thedate=" . $date;

        $response = $this->httpClient->sendGetRequest($url , [], $this->getHeaderKKOrder());

        $html = $response->getBody()->getContents();

        $html = preg_replace('/<script\b[^>]*>(.*?)<\/script>/is', '', $html);

        $html = preg_replace('/<style\b[^>]*>(.*?)<\/style>/is', '', $html);

        var_dump($html);
        try {
            $dom = HtmlDomParser::str_get_html($html);
            foreach($dom->find('.account-c') as $item) {
                $trs = $item->find('tr');
                var_dump(count($trs));
                if (count($trs) == 1) {
                    var_dump("今日无数据反馈");
                    break;
                }
                foreach($trs as $trIndex => $tr) {
                    if ($trIndex == 0) {
                        continue;
                    }
                    $tds = $tr->find('td');
                    $item = [];
                    foreach ($tds as $index => $td) {
                        if ($index == 2) {
                            $account = $td->innertext();
                            $item[$index] = explode('_', $account)[3];
                        } else {
                            $item[$index] = $td->innertext();
                        }
                    }
                    var_dump($item);
                    BaseService::simpleTransaction(function () use ($item, $date) {
                        KsDayIncome::uploadIncome($item, $date);
                    });

                    // TODO  存储UC 计算手机
                }
            }
        }catch (\Exception $e) {
            var_dump($e->getMessage(), $e->getTraceAsString());
        }
    }

    public function getOrderByDate($date)
    {
        $url = "https://union.uc.cn/account_manage/mycount_site.php?pid=1&thedate=" . $date;

        $response = $this->httpClient->sendGetRequest($url , [], $this->getHeaderOrder());
        $str = $response->getBody()->getContents();
        try {
            $dom = HtmlDomParser::str_get_html($str);
            foreach($dom->find('.account-c') as $item) {
                $trs = $item->find('tr');
                var_dump(count($trs));
                if (count($trs) == 1) {
                    var_dump("今日无数据反馈");
                    break;
                }
                foreach($trs as $trIndex => $tr) {
                    if ($trIndex == 0) {
                        continue;
                    }
                    $tds = $tr->find('td');
                    $item = [];
                    foreach ($tds as $index => $td) {
                        if ($index == 2) {
                            $account = $td->innertext();
                            $item[$index] = explode('_', $account)[3];
                        } else {
                            $item[$index] = $td->innertext();
                        }
                    }
                    var_dump($item);
                    UcDayIncome::uploadIncome($item, $date);
                    // TODO  存储UC 计算手机
                }
            }
        }catch (\Exception $e) {
            var_dump($e->getMessage(), $e->getTraceAsString());
        }
    }
}